/**
 * Created by DukeCrushIt on 2015/8/5.
 */
class FrameMgr extends egret.HashObject {
    public constructor() {
        super();
        this.items = [];
        this.itemMap = {};
    }
    public itemMap:Object;
    private items:FrameItem[];
    private stage:egret.Stage;
    public referTime:number;
    public initStage(stage:egret.Stage){
        this.stage = stage;
        this.stage.addEventListener(egret.Event.ENTER_FRAME,this.update, this);
        this.referTime = egret.getTimer();
    }

    public update(evt:egret.Event){
        var temp:number = egret.getTimer();
        var delta:number = temp - this.referTime;
        var len:number = this.items.length;
        var item:FrameItem;
        for(var idx = len-1; idx >= 0; idx--){
            item = this.items[idx];
            if( item && item.callFun && item.callObj)
                item.callFun.call(item.callObj,delta);
            if( len != this.items.length){
                //console.log("hehe");
            }
        }
        this.referTime = temp;
        Model.SYSTIME += delta;
    }

    public addControll(item:FrameItem){
        if( this.items.indexOf(item) == -1){
            this.items.push(item);
            this.itemMap[item.callObj.name] = item;
        }
    }

    public delController(name:string){
        if( this.items.length == 0 ) return;
        var item:FrameItem = this.itemMap[name];
        if( item != null && item != undefined){
            var idx:number = this.items.indexOf(item);
            if(idx != -1){
                this.items.splice(idx,1);
            }
        }
        delete this.itemMap[name];
    }

    public isUnderControl(name:string):boolean{
        return this.itemMap[name] != undefined && this.itemMap[name] != null;
    }

    public pause(){
        this.stage.removeEventListener(egret.Event.ENTER_FRAME,this.update, this);
    }

    public resume(){
        this.referTime = egret.getTimer();
        this.stage.addEventListener(egret.Event.ENTER_FRAME,this.update, this);
    }

    private static _instance:FrameMgr;
    public static getInstance():FrameMgr{
        if( FrameMgr._instance == null)
            FrameMgr._instance = new FrameMgr();
        return FrameMgr._instance;
    }
}